<?php
namespace core;
use core\Xml;
/**
 * 短信处理类
 * @package     tools_class
 *
 */
class Msg{

	static public $instance;
	static public function getinstance(){
		if(!self::$instance) self::$instance = new self();
		return self::$instance;
	}

	public function sendSMS($mobiles,$data = array(),$template,$flag = null,$debug = null){
		$mobiles	=	isset($mobiles)		? $mobiles		:'';
		$data	=		isset($data)		? $data			:'';
		$template	=	isset($template)	? $template		:'';
		$flag		=	isset($flag)		? $flag			:'';
		$tt="ce shi";
		if(empty($mobiles) or empty($data) or empty($template) ){
			return false;
		}
		$check=db('msg')
			->where('phone',$mobiles)
			->where('now()-addtime<60')
			->order('id desc')
			->find();
		if(!empty($check)){ exit; }

		$res=db('msg_template')->where('id',$template)->find();
		$content=$res['content'];

		foreach($data as $d){
			$content = preg_replace('/【变量】/', $d, $content, 1);
		}
		//echo $content."<br>";
		$content=urlencode($content);
		$url='http://106.ihuyi.cn/webservice/sms.php?method=Submit&account=cf_chaolu&password=yBhweM&mobile='.$mobiles.'&content='.$content;

		if(empty($debug)){
			$ch = curl_init();
			$timeout = 5;
			curl_setopt ($ch, CURLOPT_URL, $url);
			curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
			$file_contents = curl_exec($ch);
			curl_close($ch);
		}else{
			$file_contents="<?xml version=\"1.0\" encoding=\"utf-8\"?><SubmitResult xmlns=\"http://106.ihuyi.cn/\"><code>2</code><msg>测试成功</msg><smsid>000000</smsid></SubmitResult>";
		}

		$tst=new Xml();
		$d=$tst->toArray($file_contents);
		$insert_data = array();
		$insert_data['phone'] = $mobiles;
		$insert_data['code']  = $d['code'][0];
		$insert_data['msg']   = $d['msg'][0];
		$insert_data['smsid'] = $d['smsid'][0];
		$insert_data['content'] = urldecode($content);
		$insert_data['addtime'] = date("Y-m-d H:i:s");
		$insert_data['is_show'] = '1';
		$insert_data['ip'] = $_SERVER['REMOTE_ADDR'];
		db('msg')->insert($insert_data);

		if($flag==1){
			if( $d['code'][0]==2 ){
				$insert_code_data = array();
				$insert_code_data['phone'] = $mobiles;
				$insert_code_data['code'] = $data[0];
				$insert_code_data['createAt'] = time();
				$insert_code_data['expireAt'] = time()+1800;
				$insert_code_data['IP'] = $_SERVER['REMOTE_ADDR'];
				db('msg_code')->insert($insert_code_data);
			}
		}

		return $d;
	}

	//短信精灵接口
	public function sms_get($url){
		$ch = curl_init();
		$timeout = 5;
		curl_setopt ($ch, CURLOPT_URL, $url);
		curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
		$file_contents = curl_exec($ch);
		curl_close($ch);
		return $file_contents;
	}
	public function GetNum(){
		$url="http://106.ihuyi.cn/webservice/sms.php?method=GetNum&account=cf_chaolu&password=yBhweM";
		$result=$this->sms_get($url);
		$tst=new Xml();
		$d=$tst->toArray($result);
		return $d['num'][0];

	}

}